name: Test and Deploy JS Files

on:
  push:
    branches: [ main ]
    paths:
      - 'src/**/*.js'
      - 'package.json'
      - 'package-lock.json'
  pull_request:
    branches: [ main ]
    paths:
      - 'src/**/*.js'
      - 'package.json'
      - 'package-lock.json'
  workflow_dispatch:  # Enables manual triggering

permissions:
  contents: read  # Default read-only access to repository contents

jobs:
  test-and-deploy:
    runs-on: ubuntu-latest
    
    permissions:
      contents: read  # Read access to checkout the source repository
      # Note: Write access to destination repo is handled via PAT_TOKEN
    
    steps:
    - name: Checkout source repo (PodletJS)
      uses: actions/checkout@v4
      with:
        path: source

    - name: Check if lock file exists
      id: check_lock
      run: |
        if [ -f source/package-lock.json ]; then
          echo "lockfile-exists=true" >> $GITHUB_OUTPUT
        else
          echo "lockfile-exists=false" >> $GITHUB_OUTPUT
        fi

    - name: Setup Node.js with cache
      if: steps.check_lock.outputs.lockfile-exists == 'true'
      uses: actions/setup-node@v4
      with:
        node-version-file: 'source/package.json'
        cache: 'npm'
        cache-dependency-path: 'source/package-lock.json'

    - name: Setup Node.js without cache
      if: steps.check_lock.outputs.lockfile-exists == 'false'
      uses: actions/setup-node@v4
      with:
        node-version-file: 'source/package.json'
        
    - name: Install dependencies
      run: |
        cd source
        npm ci
      
    - name: Run tests
      run: |
        cd source
        npm test
      
    - name: Checkout destination repo
      uses: actions/checkout@v4
      with:
        repository: karoltheguy/karoltheguy.github.io
        token: ${{ secrets.PAT_TOKEN }}
        path: destination
        
    - name: Copy JS files from src to destination js folder
      run: |
        # Create js directory if it doesn't exist
        mkdir -p destination/js
        
        # Copy all JS files from source/src folder to destination js folder
        cp source/src/*.js destination/js/
        
    - name: Commit and push to destination repo
      run: |
        cd destination
        git config --local user.email "action@github.com"
        git config --local user.name "GitHub Action"
        git add js/
        if ! git diff --staged --quiet; then
          git commit -m "Update JS files from PodletJS repo"
          git push
        else
          echo "No changes to commit"
        fi
